package com.baosight.risk.common.freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import java.util.UUID;

/**
 * @author houji
 */
@Slf4j
public class ResumeWord {
//    private static Configuration configuration = null;
//    private static Map<String, Template> allTemplate = null;
//
//    static {
//        configuration = new Configuration(Configuration.VERSION_2_3_0);
//        configuration.setDefaultEncoding("UTF-8");
//        configuration.setClassForTemplateLoading(ResumeWord.class, "/template");
////        try {
////            configuration.setDirectoryForTemplateLoading(new File("E:\\"));
////        } catch (IOException e1) {
////            log.error(e.getMessage());
////        }
//        allTemplate = new HashMap<String, Template>();
//        try {
//            allTemplate.put("finish", configuration.getTemplate("finish.ftl"));
//            allTemplate.put("import", configuration.getTemplate("import.ftl"));
//            allTemplate.put("report", configuration.getTemplate("report.ftl"));
//            allTemplate.put("ridc",configuration.getTemplate("ridcRisk.ftl"));
//            allTemplate.put("mainReport",configuration.getTemplate("mainReport.ftl"));
//        } catch (IOException e) {
//            log.error(e.getMessage());
//            throw new RuntimeException(e);
//        }
//    }

    private ResumeWord() {
    }

    public static File createDoc(Map<?, ?> dataMap, String template, String name) {
        String fileName = UUID.randomUUID() + "_" + name + ".doc";
        File f = new File(fileName);
        Writer w = null;
        try {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            configuration.setDefaultEncoding("UTF-8");
            configuration.setClassForTemplateLoading(ResumeWord.class, "/template");
            Template t = configuration.getTemplate(template);
            //这个地方不能使用FileWriter因为需要指定编码类型否则生成的word文档会因为有无法识别的编码而无法打开
            w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            try {
                w.close();
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
        return f;
    }
}
